<template>
  <div class="page-container page-footer-btn">
    <van-cell-group>
      <!-- <van-field is-link @click="showPopup" placeholder="请选择试剂组" label="试剂组" :value="form.reagentTeamName"></van-field> -->
      <van-popup v-model="show" position="right" class="popup">
        <van-search v-model="form.reagentTeamName" placeholder="请输入关键词" shape="round"  background="#1989fa" @input="whfilter" />
        <van-checkbox-group>
          <van-cell-group>
            <van-cell
              v-for="(item, index) in searchedList"
              clickable
              :key="item.id"
              :title="item.name"
              @click="deptCheck(item, index)"
            >
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </van-popup>

      <FortenScan
        ref="scanDom"
        :propPlaceholder="`${this.form.useType == 'MANUAL' ? '请扫描试剂条码' : '请先扫描检验设备条码或试剂条码'}`"
        propErrorMsg="请扫描正确的SN/RFID"
        :propTypeArr="['sn','rfid','GTIN']"
        @scanCall="handleScanOver"
      />
      <van-row>
        <van-field label="消耗类型：" placeholder="请选择:" @click="useTypeShow = true" is-link label-align="left" v-model="form.useTypeName" size="mini" readonly/>
        <!-- <van-cell is-link :title="'消耗类型：'+form.useTypeName" placeholder="请选择:" @click="useTypeShow = true" /> -->
        <van-action-sheet v-model="useTypeShow" :actions="actions" @select="onSelect" />
      </van-row>
      <van-row>
        <van-field label="所属试剂组：" label-align="left" v-model="form.reagentTeamName" size="mini" readonly is-link @click="showPopup"/>
      </van-row>
      <van-row gutter="20">
        <van-col span="12">
          <van-field label="设备编码：" label-align="left" v-model="form.equipmentCode" size="mini" readonly/>
        </van-col>
        <van-col span="12">
          <van-field label="设备名称：" label-align="left" v-model="form.equipmentName" size="mini" readonly/>
        </van-col>
      </van-row>
    </van-cell-group>
    <van-divider><span style="font-size:16px;color:black;">消耗明细列表</span></van-divider>
    <van-row>
      <van-col span="8"><span>合计</span></van-col>
      <van-col span="8"><span>数量：{{itemsQty}}</span></van-col>
      <van-col span="8"><span>金额：{{itemsAmount}}</span></van-col>
    </van-row>
    <van-divider :hairline="false"/>

    <div class="items-container">
      <UseItem
        style="margin-top:5px;"
        v-for="item in formItems"
        :key="item.id"
        :value="item"
        v-on:delete="deleteItem(item)"
      />
    </div>

    <van-row  class="footer-btn" type="flex" justify="space-around">
      <van-col span="6">
        <van-button text="提交" type="primary" @click="handleSubmit"></van-button>
      </van-col>
      <van-col span="6">
        <van-button text="取消" type="danger" @click="handleCancel"></van-button>
      </van-col>
    </van-row>

  </div>
</template>

<script>
/* eslint-disable*/
import { Button , Popup, Sticky, List, Image as VanImage, NumberKeyboard, DatetimePicker, Swipe, SwipeItem, RadioGroup, Radio, Checkbox, CheckboxGroup   } from 'vant'
import Vue from 'vue'
import FlowButtons from '@/components/FlowButtons.vue'
import UseItem from './DeptUseItem.vue'
import barcodeParse from '@/util/barcodeParse.js'

Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(DatetimePicker)
Vue.use(VanImage)
Vue.use(NumberKeyboard)
Vue.use(List)
Vue.use(Popup)

export default {
  data() {
    return {
      form: {},
      formItems: [],
      images: [],
      searchedList: [],
      result: [],
      stockIds: [],
      ids: [],
      searchValue: '',
      scan: '',
      show: false,
      useTypeShow: false
    }
  },
  props: {
    propFlowKey: String
  },
  mounted() {
    this.$refs.scanDom && this.$refs.scanDom.focus()
    this.getBaseData()
  },
  computed: {
    actions() {
      return this.utils.getDictDataList('use_reagent_type').filter(dict => dict.value == 'MANUAL' || dict.value == 'EQUIPMENT').map(dict => {
        return { name: dict.label, value: dict.value }
      })
    },
    itemsQty() {
      let itemsQty = 0
      this.formItems && this.formItems.forEach(item => {
        itemsQty += item.useQty
      })
      return itemsQty
    },
    itemsAmount() {
      let itemsAmount = 0
      this.formItems && this.formItems.forEach(item => {
        itemsAmount += item.skuPrice
      })
      return itemsAmount
    }
  },
  methods: {
    // 右上角刷新按钮回调
    reload() {
      this.clearForm()
    },
    getBaseData(){
      this.getDept()
      this.getReagentTeam()
      this.$set(this.form, 'useType', 'MANUAL')
      const find = this.actions.find(a => a.value == 'MANUAL')
      this.$set(this.form, 'useTypeName', find.name || '')
    },
    getDept(){
      const currentUser = this.$store.getters.currentUser.currentUser
      this.$set(this.form, 'deptName', currentUser.deptName)
      this.$set(this.form, 'deptId', currentUser.deptId)
    },
    getReagentTeam(){
      this.$ajax.get('/base/reagent_team/currentTeam').then(res => {
        this.utils.loadHide()
        if(res.code == 0){
          this.searchedList = res.data || []
          if (this.searchedList.length == 1) {
            // 如果当前用户只属于一个专业组，则默认第一个专业组
            this.$set(this.form, 'reagentTeamId', this.searchedList[0].id)
          }
        }
      }).catch(err=> {
        this.utils.loadHide()
      })
    },
    deleteItem(value){
      this.formItems.splice(this.formItems.indexOf(value), 1)
      this.stockIds = this.stockIds.filter(id => id !== value.stockId)
    },
    handleScanClear(event) {
      this.scan = ''
    },
    showPopup() {
      this.show = true;
      this.utils.loadShow()
      this.getReagentTeam()
    },
    handleScanOver(scanValue) {
      if (!this.form.reagentTeamId) {
        this.scan = ''
        this.$notify.warning('请选择所属试剂组')
        return
      }
      let codeType = ''
        codeType = barcodeParse.barCodeType(scanValue)
      if (this.form.useType == 'EQUIPMENT' || codeType == 'GTIN') {
        // 是否检验设备
        this.getINS(scanValue, codeType)
      } else if (this.form.useType == 'MANUAL' && (codeType == 'SN' || codeType == 'RFID')) {
          this.getByCode(scanValue,codeType)
        } else {
        this.$notify.warning('请扫描有效的检验试剂条码')
        this.utils.loadHide()
          window.scanError()
          return
      }
      this.scan = null
    },
    getByCode(code,codeType){
      if (this.form.useType == 'EQUIPMENT' && !this.form.equipmentCode) {
        this.$notify.warning('请先扫描检验设备编码')
        return
      }
      let wrapper = this.$newWrapper().eq(codeType.toLowerCase(), code).gt('packageQty', 0)
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions),
      }
      this.$ajax.get('/wm/tertiary_stock/list', { params }).then((resp) => {
        if (resp.data.length === 0) {
          this.$notify.warning('请扫描有效的试剂条码')
          this.utils.loadHide()
          return
        }
        let stock = resp.data[0]
        if (this.form.reagentTeamId != stock.reagentTeamId) {
          this.scan = ''
          this.$notify.warning('扫描的试剂不属于当前试剂组，不能进行消耗')
          return
        } else {
          this.getItem(stock.id, code)
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    getINS(code, codeType) {
      let wrapper = this.$newWrapper().eq('sn', code)
      let params = {
        queryString: JSON.stringify(wrapper.queryConditions),
      }
      this.$ajax.get('/base/inspection_equipment/list', { params }).then((resp) => {
        if (resp.data.length === 0) {
          if (codeType == 'SN' || codeType == 'RFID') {
            this.getByCode(code, codeType)
          } else {
            this.$notify.warning('请扫描有效的检验设备编码或试剂条码')
          this.utils.loadHide()
          }
          return
        }

        const ins = resp.data[0]
        if (this.form.reagentTeamId != ins.reagentTeamId) {
          this.scan = ''
          this.$notify.warning('扫描的检验设备不属于当前试剂组，不能进行消耗')
          return
        } else if (!ins.flagTesting) {
          this.scan = ''
          this.$notify.warning('扫描的设备不是检验试剂设备，请重新扫描')
        } else {
          if(this.form.equipmentCode && this.form.equipmentCode != ins.code) {
            this.clearForm()
          }
          this.$set(this.form, 'equipmentCode', ins.code)
          this.$set(this.form, 'equipmentName', ins.name)
          const find = this.actions.find(a => a.value == 'EQUIPMENT')
          this.$set(this.form, 'useType', 'EQUIPMENT')
          this.$set(this.form, 'useTypeName', find.name || '')
        }
      }).catch(err => {
        this.utils.loadHide()
      })
    },
    getItem(stockId, code){
      const exist = this.formItems.find(i => i.sn === code)
      if (exist) {
        // 同样的sn再扫一次，直接删除
        this.formItems.splice(this.formItems.indexOf(exist), 1)
        this.stockIds = this.stockIds.filter(id => id !== stockId)
        return
      }
      this.utils.loadShow()
      const params = {
        form: {
          useType: this.form.useType,
          deptId: this.form.deptId,
          reagentTeamId: this.form.reagentTeamId,
          reagentTeamName: this.form.reagentTeamName,
          equipmentCode: this.form.equipmentCode || ''
        },
        stockId: stockId
      }
      this.$ajax.post('/dept/use_reagent/getBySn', params).then((resp) => {
        if (resp.code == 0) {
          this.scan = ''
          this.formItems.push({ ...resp.data, stockId: stockId})
          this.stockIds.push(stockId)
        }
        this.utils.loadHide()
      })
      .catch(() => {
        this.utils.loadHide()
      })
    },
    clearForm() {
      this.formItems = []
      this.stockIds = []
      this.scan = ''
      this.$refs.scanDom && this.$refs.scanDom.focus()
    },
    whfilter() {
      this.searchedList = this.searchedList.filter(item => item.name.indexOf(this.form.reagentTeamName) > -1
        || this.pyutils.chineseToPinYin(item.name).indexOf(this.form.reagentTeamName) > -1)
    },
    deptCheck(item, index){
      if (this.form.reagentTeamId == item.id) {
        this.show = false
        return
      }
      this.reCheck(item)
    },
    reCheck(item){
      this.clearForm()
      this.getDept()
      this.$set(this.form, 'reagentTeamId' , item.id)
      this.$set(this.form, 'reagentTeamName' , item.name)
      this.$set(this.form, 'equipmentCode', '')
      this.$set(this.form, 'equipmentName', '')
      this.show = false
    },
    handleSubmit() {
      if(!this.form.reagentTeamId) {
        this.$notify.warning('请选择所属试剂组')
        return
      }
      if(!this.formItems || this.formItems.length == 0) {
        this.$notify.warning('消耗明细不能为空，请扫描试剂SN/RFID')
        return
      }
      this.formItems.forEach(item => item.useType = this.form.useType)
      const params = {
        stockIds: this.stockIds,
        items: this.formItems
      }
      this.utils.loadShow()
      this.$ajax.post('/dept/use_reagent/saveItems', params).then((resp) => {
        if (resp.code == 0) {
          this.$notify.success('操作成功')
          this.clearForm()
        }
        this.utils.loadHide()
      }).catch(() => {
        this.utils.loadHide()
      })
    },
    handleCancel() {
      this.form = {}
      this.clearForm()
      this.$router.go(-1)
    },
    onSelect(action, index) {
      if (this.form.useType && this.form.useType != action.value) {
        this.clearForm()
        this.$set(this.form, 'equipmentCode', '')
        this.$set(this.form, 'equipmentName', '')
      }
      this.$set(this.form, 'useType', action.value)
      this.$set(this.form, 'useTypeName', action.name)
      this.useTypeShow = false
    }
  },
  components: {
    UseItem,
    FlowButtons,
    RadioGroup,
    Sticky,
    Checkbox,
    CheckboxGroup,
    Radio,
    Button
  }

}
</script>

<style lang="scss" scoped>
  .items-container {
    min-height: 80px;
  }
  .popup {
    width: 80%;
    height: 100%;
  }
  .footer{
    position: fixed;
    left: 0px;
    bottom: 0px;
    width: 100%;
    height: 50px;
  }
  .btn-container {
    margin-left: 1%;
    margin-right: 1%;
    flex-direction:column ;
    justify-content: space-between;
    display:inline-block;
    width: 80%;
  }
  .creat{
    margin-left: 1%;
    flex-direction:column ;
    justify-content: space-between;
  }
</style>
